import Vue from 'vue'
import VueRouter from 'vue-router'
import Layout from '@/views/layout'
import Login from '@/views/login'
import NotFound from '@/views/404'
import Home from '@/views/layout/home'
import Qa from '@/views/layout/qa'
import Video from '@/views/layout/video'
import SearchResult from '@/views/search/result'
import Detail from '@/views/article'
import User from '@/views/layout/user'
import store from '@/store'
import Search from '@/views/search'
import Edit from '@/views/layout/user/edit.vue'
import Chat from '@/views/layout/user/chat.vue'
Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    component: Layout,
    // 重定向
    redirect: '/home',
    children: [
      {
        path: 'home',
        component: Home,
        meta: {
          // !首页路由对应的组件是需要被缓存起来的
          isKeepLive: true
        }
      },
      {
        path: 'qa',
        component: Qa
      },
      {
        path: 'video',
        component: Video
      },
      {
        path: 'user',
        component: User
      }
    ]
  },
  {
    path: '/login',
    component: Login
  },
  {
    path: '/search',
    component: Search
  },
  {
    path: '/search/result',
    component: SearchResult
  },
  {
    path: '/detail/:id',
    component: Detail
  },
  {
    path: '/user/edit',
    component: Edit
  },
  {
    path: '/user/chat',
    component: Chat
  },
  {
    path: '*',
    component: NotFound
  }
]

const router = new VueRouter({
  routes
})

// !全局导航守卫=>用户没有登录就不能访问user等页面
// 1.是否有token，
// 2.有token放行(next()),
// 3.无则判断去的页面，
//   3.1若是首页/问答/视频就放行(next()),
//   3.2若是user等页面就跳转去登录页(next('/login'))
// !需要拦截的页面(需要登录才可以访问到)
const loginURL = ['/user', '/qa', '/user/edit', '/user/chat']
router.beforeEach(function (to, from, next) {
  const token = store.state.user.token.token
  // console.log(token)
  if (token) {
    next()
  } else {
    if (loginURL.some((item) => to.path === item)) {
      // next('/login') //!写next会有导航故障的报错
      // router.push('/login')
      // !活的写法
      router.push({
        path: '/login',
        query: {
          back: to.fullPath
        }
      })
    } else {
      next()
    }
  }
})

export default router
